﻿#region Init
using EFCoreManyToManyDemo;
using Microsoft.EntityFrameworkCore;

var connectionString = "server=localhost;port=5432;Database=efcoremanytomany;uid=postgres;pwd=xxx;";
var contextOptions = new DbContextOptionsBuilder<AppDbContext>()
    .UseNpgsql(connectionString)
    .Options;
using (var context = new AppDbContext(contextOptions))
{
    context.Database.EnsureDeleted();
    context.Database.EnsureCreated();
}
#endregion

#region Create
using (var context = new AppDbContext(contextOptions))
{
    var order = new Order()
    {
        Name = "aa"
    };
    order.AddProduct("bb", "bird");
    await context.Orders.AddAsync(order);
    await context.SaveChangesAsync();
}
using (var context = new AppDbContext(contextOptions))
{
    var orders = await context.Orders
        .Include(o => o.Products)
        .ToListAsync();
    Console.WriteLine($"Order count: {orders.Count}");
    Console.WriteLine($"Product name: {orders.First().Products.First().Name}");
    Console.WriteLine($"OrderItem id: {orders.First().Products.First().GetOrderItemId()}");
    Console.WriteLine($"OrderItem description: {orders.First().Products.First().GetOrderItemDescription()}");
    Console.WriteLine($"Category description: {orders.First().Products.First().GetCategoryDescription()}");
}
#endregion

#region Update
using (var context = new AppDbContext(contextOptions))
{
    var order = await context.Orders
        .Include(o => o.Products)
        .FirstAsync();

    order.SetDescription(order.Products.First().Id, "1998");
    context.Orders.Update(order);
    await context.SaveChangesAsync();
}
using (var context = new AppDbContext(contextOptions))
{
    var orders = await context.Orders
        .Include(o => o.Products)
        .ToListAsync();
    Console.WriteLine($"Order count: {orders.Count}");
    Console.WriteLine($"Product name: {orders.First().Products.First().Name}");
    Console.WriteLine($"OrderItem id: {orders.First().Products.First().GetOrderItemId()}");
    Console.WriteLine($"OrderItem description: {orders.First().Products.First().GetOrderItemDescription()}");
    Console.WriteLine($"Category description: {orders.First().Products.First().GetCategoryDescription()}");
}
#endregion